package jp.tkym.labs.store;

import java.sql.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class EntityResolveUtil{
	private AsType asInt = new AsType(){ 
		public Object to(Object from){ 
			if(from == null) return null;
			return ((Long)from).intValue(); 
		} 
	};
	private AsType noChange = new AsType(){ 
		public Object to(Object from){ 
			if(from == null) return null;
			return from; 
		} 
	};
	private AsType asShort = new AsType(){ 
		public Object to(Object from){ 
			if(from == null) return null;
			return ((Long)from).shortValue(); 
		} 
	};
	private AsType asByte = new AsType(){ 
		public Object to(Object from){ 
			if(from == null) return null;
			return ((Long)from).byteValue(); 
		} 
	};
	private AsType asDate = new AsType(){ 
		public Object to(Object from){ 
			if(from == null) return null;
			return new Date((Long)from);
		} 
	};

	private Set<Class<?>> resolveKeyById = new HashSet<Class<?>>();
	private Set<Class<?>> resolveKeyByName = new HashSet<Class<?>>();
	private Map<Class<?>, AsType> asTypeMap = new HashMap<Class<?>, AsType>(); 
	private static final EntityResolveUtil singleton = new EntityResolveUtil();
	
	private EntityResolveUtil(){
		asTypeMap.put(int.class, asInt);
		asTypeMap.put(Integer.class, asInt);
		asTypeMap.put(Long.class, noChange);
		asTypeMap.put(long.class, noChange);
		asTypeMap.put(Short.class, asShort);
		asTypeMap.put(short.class, asShort);
		asTypeMap.put(Byte.class, asByte);
		asTypeMap.put(byte.class, asByte);
		asTypeMap.put(Date.class, asDate);
		resolveKeyById.add(long.class);
		resolveKeyByName.add(String.class);
	}
	
	static EntityResolveUtil getInstance(){
		return singleton;
	}
	
	private AsType asType(Class<?> type){
		AsType asType = asTypeMap.get(type);
		if(asType == null) return noChange;
		return asType;
	}
	
	Object convertFrom(Class<?> type, Object entityValue){
		return asType(type).to(entityValue);
	}
	private interface AsType{
		Object to(Object from);
	}
	
	public static enum KeyResolveType{
		ID, NAME, NONE
	}

	public KeyResolveType resolveKeyType(Class<?> cls){
		if(resolveKeyById.contains(cls)) return KeyResolveType.ID;
		if(resolveKeyByName.contains(cls)) return KeyResolveType.NAME;
		return KeyResolveType.NONE;
	}
}